<?php
namespace App\Http\Controllers;

use App\Models\Act;
use App\Models\ActPrize;
use App\Models\ActType;
use App\Models\ActWinners;
use Illuminate\Http\Request;
use App\Models\ActPrizeSetting;
use \DB;
use App\Http\Requests\ActRequest;
use \Excel;
class ActController extends CommonController
{

    /**
     *获取列表
     */
    public function getIndex()
    {
        $lists = Act::with('type')->orderBy('created_at', 'desc')->paginate(10);

        return view('act.index')->with("lists", $lists)->with("actions", $this->actions)->with("wjtrUrl", $this->wjtrUrl);
    }

    /**
     * @param Request $request
     * 导出该次活动的获奖者名单
     */
    public function getExport(Request $request)
    {
        $data = $request->input();
        $winners = ActWinners::with('act','user','prizeArray.prize')->where('act_id', $data['act_id'])->get()->toArray();
        $act = Act::where('id', $data['act_id'])->first();
        $winnersInfo = array();
        foreach($winners as $k=>$v){
//            $winnersInfo[$k]['id'] = $v['id'];
            $winnersInfo[$k]['reg_username'] = $v['user']['username'];
            $winnersInfo[$k]['act_name'] = $v['act']['title'];
            $winnersInfo[$k]['prize'] = $v['prize_array']['prize']['name'];
            $winnersInfo[$k]['city'] = $v['city'];
            $winnersInfo[$k]['post_username'] = $v['username'];
            $winnersInfo[$k]['post_tel'] = $v['tel'];
        }
        //表头
        $title = [["reg_username" =>'username（注册时）',"act_name" =>'活动主题',"prize" =>'奖品名',"city" =>'城市',"post_username" =>'用户名（邮寄用）',"post_tel" =>'电话（邮寄用）'],];
        $winnersInfo = array_merge($title, $winnersInfo);
        Excel::create('活动“'.$act->title.'”的获奖者名单', function($excel) use($winnersInfo) {
            $excel->sheet('获奖者名单', function($sheet) use($winnersInfo) {
                $sheet->rows($winnersInfo);
            });
        })->export('xls');
    }

    /**
     * 执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();
        $lists = Act::orderBy('created_at');

        if (isset($data['activity_name']) && $data['activity_name'] != '') {
            $aIds = Activity::where('subject', 'like', '%' . $data['activity_name'] . '%')->lists('id');
            $lists->whereIn('activity_id', $aIds);
        }
    }

    /**
     * 获取创建页面
     */
    public function getCreate()
    {

        //一等奖
        $aPrize = ActPrize::where('type', 1)->get();
//        dd($aPrize);exit;
        //二等奖
        $bPrize = ActPrize::where('type', 2)->get();
        //三等奖
        $cPrize = ActPrize::where('type', 3)->get();

        //普通奖
        $dPrize = ActPrize::where('type', 4)->get();
        $types = ActType::get();

        return view('act.create')->with('aPrize', $aPrize)
            ->with('bPrize', $bPrize)->with('cPrize', $cPrize)
            ->with('dPrize', $dPrize)->with('types', $types);
    }

    /**
     * 获取普通奖接口
     */
    public function postDPrize(Request $request)
    {
        $data = $request->input();

        //普通奖
        $dPrize = ActPrize::where('type', 4)->get();
        if (count($dPrize)) {
            return AjaxCallbackMessage($dPrize, true);
        } else {
            return AjaxCallbackMessage('目前数据库中没有普通奖项可以用来设置', false);
        }
    }

    /**
     * 执行一个创建
     */
    public function postCreate(ActRequest $request)
    {
        $data = $request->input();

        $data['date'] = strtotime($data['date']);
//                dd($data);

        $result = Act::create(['title' => $data['title'], 'type_id' => $data['type_id'], 'date' => $data['date']]);

//        //判断是否需要设置一等奖
//        if ($data['aPrize'] && $data['aNumeric']) {
//            ActPrizeSetting::create(['act_id' => $result->id, 'prize_id' => $data['aPrize'], 'num' => $data['aNumeric']]);
//        }
//
//        //判断是否需要设置二等奖
//        if ($data['bPrize'] && $data['bNumeric']) {
//            ActPrizeSetting::create(['act_id' => $result->id, 'prize_id' => $data['bPrize'], 'num' => $data['bNumeric']]);
//        }
//
//        //判断是否需要设置三等奖
//        if ($data['cPrize'] && $data['cNumeric']) {
//            ActPrizeSetting::create(['act_id' => $result->id, 'prize_id' => $data['cPrize'], 'num' => $data['cNumeric']]);
//        }

//        //获取和普通奖项相关的元素
//        $normal = [];
//        foreach ($data as $k => $v) {
//            strpos($k, 'normal') !== false && $normal[$k] = $v;
//        }
//
//        $n = count($normal) / 2;
//        for ($i = 1; $i <= $n; $i++) {
//            if ($data['normal' . $i . 'Prize'] && $data['normal' . $i . 'Numeric']) {
//                ActPrizeSetting::create(['act_id' => $result->id, 'prize_id' => $data['normal' . $i . 'Prize'], 'num' => $data['normal' . $i . 'Numeric']]);
//            }
//        }

        return AjaxCallbackMessage('活动创建成功', true, url('act/index'));
    }

    /**
     * 获取详情页面
     */
    public function getInfo(Request $request)
    {
        $data = $request->input();

        //一等奖
        $aPrize = ActPrize::with('setting')->where('act_id', $data['id'])->where('type', 1)->first();

        //二等奖
        $bPrize = ActPrize::with('setting')->where('act_id', $data['id'])->where('type', 2)->first();

        //三等奖
        $cPrize = ActPrize::with('setting')->where('act_id', $data['id'])->where('type', 3)->first();

        //普通奖
        $dPrize = ActPrize::with('setting')->where('act_id', $data['id'])->where('type', 4)->get();

        $list = Act::with('actPrizeSetting', 'type')->where('id', $data['id'])->first();

        //获奖者
//        $winners = DB::table('act_winners')->where('act_id', )
        $winners = DB::table('act_winners')->where('act_winners.act_id', $data['id'])
            ->join('act_prize_array', 'act_winners.prize_arr_id', '=', 'act_prize_array.id')
            ->join('act_prize', 'act_prize_array.prize_id', '=', 'act_prize.id')
            ->join('user', 'act_winners.uid', '=', 'user.uid')
            ->orderBy('act_prize.type', 'desc')
            ->select('act_winners.tel', 'act_winners.username', 'act_prize.name', 'act_prize.type', 'user.realname', 'user.nickname')
            ->get();

        //活动类型
        $typeList = ActType::get();
        $num = Array('一', '二', '三', '四', '五', '六');

        return view('act.info')->with('list', $list)->with('aPrize', $aPrize)
            ->with('bPrize', $bPrize)->with('cPrize', $cPrize)->with('num', $num)
            ->with('dPrize', $dPrize)->with('typeList', $typeList)->with('winners', $winners);
    }

    /**
     * 获取编辑页面
     */
    public function getEdit(Request $request)
    {
        $data = $request->input();

        //一等奖
        $aPrize = ActPrize::where('type', 1)->get();

        //二等奖
        $bPrize = ActPrize::where('type', 2)->get();
        //三等奖
        $cPrize = ActPrize::where('type', 3)->get();

        //普通奖
        $dPrize = ActPrize::where('type', 4)->get();

        $list = Act::with('actPrizeSetting', 'type')->where('id', $data['id'])->first();
        $num = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
        //一等奖的设置
        $aPrizeSetting = ActPrizeSetting::with('prize')->whereHas(
            'prize',
            function ($q) {
                $q->where('type', 1);
            }
        )->where('act_id', $data['id'])->first();

        //二等奖的设置
        $bPrizeSetting = ActPrizeSetting::with('prize')->whereHas(
            'prize',
            function ($q) {
                $q->where('type', 2);
            }
        )->where('act_id', $data['id'])->first();

        //三等奖的设置
        $cPrizeSetting = ActPrizeSetting::with('prize')->whereHas(
            'prize',
            function ($q) {
                $q->where('type', 3);
            }
        )->where('act_id', $data['id'])->first();

        //普通奖的设置
        $dPrizeSetting = ActPrizeSetting::with('prize')->whereHas(
            'prize',
            function ($q) {
                $q->where('type', 4);
            }
        )->where('act_id', $data['id'])->get()->toArray();

        //活动类型
        $typeList = ActType::get();

        return view('act.edit')->with('list', $list)->with('aPrize', $aPrize)
            ->with('bPrize', $bPrize)->with('cPrize', $cPrize)->with('num', $num)
            ->with('aPrizeSetting', $aPrizeSetting)->with('bPrizeSetting', $bPrizeSetting)
            ->with('cPrizeSetting', $cPrizeSetting)->with('dPrizeSetting', $dPrizeSetting)
            ->with('dPrize', $dPrize)->with('typeList', $typeList);
    }

    /**
     * 执行一个编辑
     */
    public function postEdit(ActRequest $request)
    {
        $data = $request->input();
        $data['date'] = strtotime($data['date']);
//                dd($data);

//        //获取和普通奖项相关的元素
//        $normal = [];
//        foreach ($data as $k => $v) {
//            strpos($k, 'normal') !== false && $normal[$k] = $v;
//        }

//        //获取普通奖项的类别
//        $normalPrize = [];
//        foreach($normal as $k=>$v){
//            strpos($k, 'Prize') !== false && $normalPrize[$k] = $v;
//        }

//        if(count(array_flip($normalPrize))!==count($normalPrize)){
//            return AjaxCallbackMessage('您所选取的普通奖项重复了，或者您存在两个没有选择的普通奖项，请重新选择', false);
//        }

        Act::where('id', $data['act_id'])->update(['title' => $data['title'], 'type_id' => $data['type_id'], 'date' => $data['date']]);

//        ActPrizeSetting::where('act_id', $data['act_id'])->delete();

//        //判断是否需要设置一等奖
//        if ($data['aPrize'] && $data['aNumeric']) {
//            ActPrizeSetting::create(['act_id' =>  $data['act_id'], 'prize_id' => $data['aPrize'], 'num' => $data['aNumeric']]);
//        }

//        //判断是否需要设置二等奖
//        if ($data['bPrize'] && $data['bNumeric']) {
//            ActPrizeSetting::create(['act_id' =>  $data['act_id'], 'prize_id' => $data['bPrize'], 'num' => $data['bNumeric']]);
//        }

//        //判断是否需要设置三等奖
//        if ($data['cPrize'] && $data['cNumeric']) {
//            ActPrizeSetting::create(['act_id' =>  $data['act_id'], 'prize_id' => $data['cPrize'], 'num' => $data['cNumeric']]);
//        }

//        $n = count($normal) / 2;
//        for ($i = 1; $i <= $n; $i++) {
//            if ($data['normal' . $i . 'Prize'] && $data['normal' . $i . 'Numeric']) {
//                ActPrizeSetting::create(['act_id' =>  $data['act_id'], 'prize_id' => $data['normal' . $i . 'Prize'], 'num' => $data['normal' . $i . 'Numeric']]);
//            }
//        }

        return AjaxCallbackMessage('恭喜，编辑成功', true, url('act/index'));
    }

    /**
     * 执行一个删除
     */
    public function postDelete()
    {
    }
}